<template>
    <a-modal v-model:visible="visible" title="选择" :width="1000" @ok="handleOk">
        <a-form class="smart-query-form">
            <a-row class="smart-query-form-row">
                <a-form-item label="登录账号" class="smart-query-form-item">
                    <a-input style="width: 200px" v-model:value="queryForm.username" placeholder="请输入登录账号" />
                </a-form-item>

                <a-form-item class="smart-query-form-item smart-margin-left10">
                    <a-button-group>
                        <a-button type="primary" @click="onSearch">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                            查询
                        </a-button>
                        <a-button @click="resetQuery">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                            重置
                        </a-button>

                    </a-button-group>
                    <a-button type="primary" @click="tableSelectChange" style="margin-left: 10px;">
                        确定
                    </a-button>
                </a-form-item>
            </a-row>
        </a-form>
        <a-row>
            <a-col :span="8">
                <a-tree :tree-data="treeData" @select="treeSelect">
                </a-tree>
            </a-col>
            <a-col :span="16">
                <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered
                    :pagination="false" :showSorterTooltip="false"
                    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange,type:'radio' }"
                    @change="onChange">
                    <template #bodyCell="{ text, record, column }">
                        <template v-if="column.dataIndex === 'gender'">
                            {{ record.gender === 1 ? '女' : '男' }}
                        </template>
                        <template v-if="column.dataIndex === 'type'">
                            {{ type[record.type] }}
                        </template>
                        <template v-if="column.dataIndex === 'action'">
                            <div class="smart-table-operate">
                                <!-- <a-button @click="visibleChange(record)" type="link">{{record.visible===1?'隐藏':'显示'}}</a-button> -->
                                <a-button @click="deleteGoods(record)" danger type="link">删除</a-button>
                            </div>
                        </template>
                    </template>
                </a-table>
                <div class="smart-query-table-page">
                    <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
                        :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum"
                        v-model:pageSize="queryForm.pageSize" :total="total" @change="ajaxQuery"
                        @showSizeChange="ajaxQuery" :show-total="(total) => `共${total}条`" />
                </div>
            </a-col>
        </a-row>
    </a-modal>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue"
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { userApi } from '/@/api/system/user'

const props = defineProps({
    value: [Number, Array],
  });
  const emit = defineEmits(['update:value'],'change');
const visible = ref(false)
const treeData = ref([])
const columns = ref([
    {
        title: '登录账号',
        dataIndex: 'username',
    },
    {
        title: '姓名',
        dataIndex: 'displayName',
    },
    {
        title: '员工编号',
        dataIndex: 'employeeNumber',
    },
    {
        title: '部门名称',
        dataIndex: 'department',
    },
    {
        title: '职位',
        dataIndex: '无',
    },
    {
        title: '性别',
        dataIndex: 'gender',
    },
])
const queryFormState = {
    pageNum: 1,
    pageSize: 10,
    departmentId:''
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);
// 查询
function onSearch() {
    queryForm.pageNumber = 1;
    ajaxQuery();
}
// 重置查询
function resetQuery() {
    Object.assign(queryForm, queryFormState);
    ajaxQuery();
}
function showModal() {
    visible.value = true
}
// 列表数据获取
async function ajaxQuery() {
    try {
        tableLoading.value = true;
        let responseModel = await userApi.getOrgsFetch(queryForm);
        const list = responseModel.data.rows
        total.value = responseModel.data.records;
        tableData.value = list;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        tableLoading.value = false;
    }
}
function getTree(){
    userApi.getOrgsTree().then(res=>{
        treeData.value = buildTree(res.data.nodes)
    })
}
function buildTree(data) {
    const tree = [];
    const map = {};
    // 先把所有节点放入一个映射表
    data.forEach((item) => {
      map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
    });
    // 构建树
    data.forEach((item) => {
      const { parentKey } = item;
      if (parentKey === '0') {
        // 如果是根节点
        tree.push(map[item.key]);
      } else {
        // 如果有父节点，则将当前节点添加到父节点的children中
        if (map[parentKey]) {
          map[parentKey].children.push(map[item.key]);
        }
      }
    });
    return tree;
  }
  function treeSelect(value){
    console.log(value);
    if(value.length){
        queryForm.departmentId = value[0];
    }
    ajaxQuery();
  }
  // 选择表格行
const selectedRowKeyList = ref([]);
const records = ref([])
function onSelectChange(selectedRowKeys,record) {
    selectedRowKeyList.value = selectedRowKeys;
    records.value = record
}

function tableSelectChange(){
    emit('update:value', selectedRowKeyList.value);
    emit('change',records.value);
    visible.value = false;
}
defineExpose({
    showModal,
});
onMounted(() => {
    ajaxQuery();
    getTree();
});
</script>
<style scoped></style>
